<!DOCTYPE html>
<html lang="zh-CN" data-theme="light">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>微信公众号管理系统</title>
    <!-- Tailwind CSS 和 DaisyUI 5.0 -->
    <link href="https://cdn.jsdelivr.net/npm/daisyui@5" rel="stylesheet" type="text/css" />
    <script src="https://cdn.jsdelivr.net/npm/@tailwindcss/browser@4"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        // 全局配置变量
        const CONFIG = {
            API_BASE_URL: 'http://8.138.111.65:8000'
        };
        // 在页面加载前检查登录状态
        (function () {
            // 检查是否已经完成验证
            if (sessionStorage.getItem('authChecked')) {
                return; // 已经验证过，直接继续加载页面
            }

            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = '/login.html';
                return;
            }

            // 设置验证超时
            const xhr = $.ajax({
                url: CONFIG.API_BASE_URL + '/api/v1/auth/verify-token',
                method: 'POST',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                timeout: 5000, // 5秒超时
                success: function (response) {
                    // token有效，标记已验证并继续加载页面
                    sessionStorage.setItem('authChecked', 'true');
                    // 触发自定义事件表示验证完成
                    document.dispatchEvent(new Event('authVerified'));
                },
                error: function (xhr, status, error) {
                    // token无效或过期，清除本地存储并跳转到登录页
                    console.log('Token验证失败:', error);
                    localStorage.removeItem('token');
                    window.location.href = '/login.html';
                }
            });

            // 处理超时情况
            setTimeout(function () {
                if (xhr.readyState !== 4) { // 如果请求还未完成
                    xhr.abort();
                    // 超时也跳转到登录页
                    localStorage.removeItem('token');
                    window.location.href = '/login.html';
                }
            }, 5000);
        })();
    </script>
    <style>
        .menu-item {
            transition: all 0.3s ease;
        }

        .menu-item:hover {
            background-color: #ede9fe;
            transform: translateX(5px);
        }

        .menu-item.active {
            background-color: #818cf8;
            color: white;
        }

        .content-section {
            display: none;
        }

        .content-section.active {
            display: block;
        }

        .stat-card {
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1);
        }
    </style>
</head>

<body class="min-h-screen bg-gradient-to-br from-indigo-50 via-purple-50 to-pink-50">
    <div class="flex h-screen">
        <!-- 左侧导航菜单 -->
        <div class="w-64 bg-gradient-to-b from-indigo-600 to-purple-600 shadow-2xl  flex flex-col">
            <div class="p-6 border-b border-white/10">
                <h2 class="text-1/2xl font-bold text-white flex items-center">
                    <i class="fas fa-robot mr-3"></i>
                    <span>关键词匹配管理</span>
                </h2>
                <p class="text-indigo-200 text-sm mt-1">微信公众号关键词管理系统</p>
            </div>

            <div class="flex-1 py-6">
                <ul class="menu bg-transparent w-full px-4">
                    <li class="mb-2">
                        <a class="menu-item active flex items-center py-4 px-6 rounded-2xl backdrop-blur-sm bg-white/10 border border-white/20"
                            href="#" data-target="dashboard">
                            <i class="fas fa-chart-line mr-4 text-lg"></i>
                            <span class="font-medium">Dashboard</span>
                        </a>
                    </li>
                    <li class="mb-2">
                        <a class="menu-item flex items-center py-4 px-6 rounded-2xl backdrop-blur-sm bg-white/5 border border-white/10 hover:bg-white/10 transition-all"
                            href="#" data-target="keywords">
                            <i class="fas fa-key mr-4 text-lg"></i>
                            <span class="font-medium">关键词管理</span>
                        </a>
                    </li>
                    <li class="mb-2">
                        <a class="menu-item flex items-center py-4 px-6 rounded-2xl backdrop-blur-sm bg-white/5 border border-white/10 hover:bg-white/10 transition-all"
                            href="#" data-target="users">
                            <i class="fas fa-users mr-4 text-lg"></i>
                            <span class="font-medium">用户管理</span>
                        </a>
                    </li>
                </ul>
            </div>

            <div class="p-6 border-t border-white/10">
                <div class="flex items-center justify-between">
                    <div class="flex items-center">
                        <div class="avatar placeholder mr-3">
                            <div
                                class="bg-white text-indigo-600 rounded-full w-12 h-12 flex items-center justify-center">
                                <i class="fas fa-user text-xl relative top-3 left-1/3"></i>
                            </div>
                        </div>
                        <div>
                            <p id="username" class="font-semibold text-white">管理员</p>
                            <p id="email" class="text-indigo-200 text-xs">admin@example.com</p>
                        </div>
                    </div>
                    <button class="btn btn-sm btn-ghost text-white hover:bg-white/10" id="logoutBtn">
                        <i class="fas fa-sign-out-alt"></i>
                    </button>
                </div>
                <div class="mt-4 pt-4 border-t border-white/10 text-center">
                    <p class="text-indigo-200 text-xs">© 2023 微信公众号管理</p>
                </div>
            </div>
        </div>

        <!-- 右侧内容区域 -->
        <div class="flex-1 flex flex-col overflow-hidden">
            <!-- 顶部导航 -->
            <div class="bg-gradient-to-r from-indigo-500 to-purple-500 shadow-sm p-4">
                <div class="flex justify-between items-center">
                    <h2 class="text-2xl font-bold text-white flex items-center">
                        <i class="fas fa-home mr-3"></i>
                        <span id="pageTitle">Dashboard</span>
                    </h2>
                </div>
            </div>

            <!-- 主要内容区域 -->
            <div class="flex-1 overflow-y-auto p-6">
                <!-- Dashboard内容 -->
                <div id="dashboard" class="content-section active">
                    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
                        <div class="stat-card bg-white rounded-2xl shadow-lg p-6">
                            <div class="flex items-center">
                                <div class="avatar placeholder mr-4">
                                    <div
                                        class="bg-indigo-100 text-indigo-500 rounded-full w-12 h-12 flex items-center justify-center">
                                        <i class="fas fa-users text-xl relative top-3 left-3"></i>
                                    </div>
                                </div>
                                <div>
                                    <p class="text-gray-500">总用户数</p>
                                    <h3 class="text-2xl font-bold">1,258</h3>
                                </div>
                            </div>
                        </div>

                        <div class="stat-card bg-white rounded-2xl shadow-lg p-6">
                            <div class="flex items-center">
                                <div class="avatar placeholder mr-4">
                                    <div
                                        class="bg-purple-100 text-purple-500 rounded-full w-12 h-12 flex items-center justify-center">
                                        <i class="fas fa-key text-xl relative top-3 left-1/3"></i>
                                    </div>
                                </div>
                                <div>
                                    <p class="text-gray-500">关键词数</p>
                                    <h3 class="text-2xl font-bold">42</h3>
                                </div>
                            </div>
                        </div>

                        <div class="stat-card bg-white rounded-2xl shadow-lg p-6">
                            <div class="flex items-center">
                                <div class="avatar placeholder mr-4">
                                    <div
                                        class="bg-pink-100 text-pink-500 rounded-full w-12 h-12 flex items-center justify-center">
                                        <i class="fas fa-comments text-xl relative top-3 left-3"></i>
                                    </div>
                                </div>
                                <div>
                                    <p class="text-gray-500">今日消息</p>
                                    <h3 class="text-2xl font-bold">326</h3>
                                </div>
                            </div>
                        </div>

                        <div class="stat-card bg-white rounded-2xl shadow-lg p-6">
                            <div class="flex items-center">
                                <div class="avatar placeholder mr-4">
                                    <div
                                        class="bg-green-100 text-green-500 rounded-full w-12 h-12 flex items-center justify-center">
                                        <i class="fas fa-check-circle text-xl relative top-3 left-3"></i>
                                    </div>
                                </div>
                                <div>
                                    <p class="text-gray-500">响应率</p>
                                    <h3 class="text-2xl font-bold">98%</h3>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="bg-white rounded-2xl shadow-lg p-6">
                        <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-4">
                            <h3 class="text-xl font-bold text-gray-800 flex items-center">
                                <i class="fas fa-chart-line text-indigo-500 mr-2"></i>消息统计
                            </h3>
                            <div class="flex gap-2">
                                <button class="btn btn-sm btn-outline rounded-lg">本周</button>
                                <button class="btn btn-sm btn-outline rounded-lg">本月</button>
                                <button class="btn btn-sm btn-primary rounded-lg">本年</button>
                            </div>
                        </div>
                        <div class="rounded-xl bg-gradient-to-r from-indigo-50 to-purple-50 p-4">
                            <canvas id="messageChart" height="100"></canvas>
                        </div>
                        <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mt-6">
                            <div class="bg-indigo-50 rounded-xl p-4">
                                <p class="text-indigo-500 text-sm">今日消息</p>
                                <p class="text-2xl font-bold">326</p>
                            </div>
                            <div class="bg-purple-50 rounded-xl p-4">
                                <p class="text-purple-500 text-sm">本周消息</p>
                                <p class="text-2xl font-bold">2,180</p>
                            </div>
                            <div class="bg-pink-50 rounded-xl p-4">
                                <p class="text-pink-500 text-sm">本月消息</p>
                                <p class="text-2xl font-bold">8,940</p>
                            </div>
                            <div class="bg-green-50 rounded-xl p-4">
                                <p class="text-green-500 text-sm">平均响应</p>
                                <p class="text-2xl font-bold">1.2s</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 关键词管理内容 -->
                <div id="keywords" class="content-section">
                    <div class="bg-white rounded-2xl shadow-lg p-6">
                        <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-4">
                            <h3 class="text-xl font-bold text-gray-800 flex items-center">
                                <i class="fas fa-key text-indigo-500 mr-2"></i>关键词列表
                            </h3>
                            <!-- 将原来的按钮替换为这个 -->
                            <button
                                class="btn btn-primary rounded-xl px-6 py-2 bg-gradient-to-r from-indigo-500 to-purple-500 border-0 hover:shadow-lg transition-all"
                                id="showAddKeywordModal">
                                <i class="fas fa-plus mr-2"></i>添加关键词
                            </button>
                        </div>

                        <div class="overflow-x-auto rounded-xl border border-gray-200">
                            <table class="table w-full">
                                <thead class="bg-gradient-to-r from-indigo-50 to-purple-50">
                                    <tr>
                                        <th
                                            class="py-4 px-6 text-left text-sm font-semibold text-indigo-700 uppercase tracking-wider">
                                            <i class="fas fa-font mr-2"></i>关键词名称
                                        </th>
                                        <th
                                            class="py-4 px-6 text-left text-sm font-semibold text-indigo-700 uppercase tracking-wider">
                                            <i class="fas fa-comment mr-2"></i>回复的内容
                                        </th>
                                        <th
                                            class="py-4 px-6 text-left text-sm font-semibold text-indigo-700 uppercase tracking-wider">
                                            <i class="fas fa-sort-numeric-up mr-2"></i>优先级
                                        </th>
                                        <th
                                            class="py-4 px-6 text-left text-sm font-semibold text-indigo-700 uppercase tracking-wider">
                                            <i class="fas fa-toggle-on mr-2"></i>状态
                                        </th>
                                        <th
                                            class="py-4 px-6 text-left text-sm font-semibold text-indigo-700 uppercase tracking-wider">
                                            <i class="far fa-calendar-plus mr-2"></i>创建的时间
                                        </th>
                                        <th
                                            class="py-4 px-6 text-right text-sm font-semibold text-indigo-700 uppercase tracking-wider">
                                            <i class="fas fa-cog mr-2"></i>操作
                                        </th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-gray-200">
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                <!-- 用户管理内容 -->
                <div id="users" class="content-section">
                    <div class="bg-white rounded-2xl shadow-lg p-6">
                        <div class="flex flex-col sm:flex-row justify-between items-start sm:items-center mb-6 gap-4">
                            <h3 class="text-xl font-bold text-gray-800 flex items-center">
                                <i class="fas fa-users text-indigo-500 mr-2"></i>用户列表
                            </h3>
                            <button
                                class="btn btn-primary rounded-xl px-6 py-2 bg-gradient-to-r from-indigo-500 to-purple-500 border-0 hover:shadow-lg transition-all">
                                <i class="fas fa-plus mr-2"></i>添加用户
                            </button>
                        </div>

                        <div class="overflow-x-auto rounded-xl border border-gray-200">
                            <table class="table w-full">
                                <thead class="bg-gray-50">
                                    <tr>
                                        <th class="py-4 px-6 text-left text-sm font-semibold text-gray-600">用户名</th>
                                        <th class="py-4 px-6 text-left text-sm font-semibold text-gray-600">邮箱</th>
                                        <th class="py-4 px-6 text-left text-sm font-semibold text-gray-600">角色</th>
                                        <th class="py-4 px-6 text-left text-sm font-semibold text-gray-600">状态</th>
                                        <th class="py-4 px-6 text-left text-sm font-semibold text-gray-600">最后登录</th>
                                        <th class="py-4 px-6 text-right text-sm font-semibold text-gray-600">操作</th>
                                    </tr>
                                </thead>
                                <tbody class="divide-y divide-gray-200">
                                    <tr class="hover:bg-indigo-50 transition-colors">
                                        <td class="py-4 px-6 font-medium">admin</td>
                                        <td class="py-4 px-6 text-gray-600">admin@example.com</td>
                                        <td class="py-4 px-6 text-gray-600">管理员</td>
                                        <td class="py-4 px-6">
                                            <div class="badge badge-success badge-outline py-2 px-3 rounded-full">启用
                                            </div>
                                        </td>
                                        <td class="py-4 px-6 text-gray-500">2023-05-20 14:30</td>
                                        <td class="py-4 px-6 text-right">
                                            <div class="flex justify-end space-x-2">
                                                <button class="btn btn-sm btn-info rounded-lg">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button class="btn btn-sm btn-error rounded-lg">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                    <tr class="hover:bg-indigo-50 transition-colors">
                                        <td class="py-4 px-6 font-medium">editor</td>
                                        <td class="py-4 px-6 text-gray-600">editor@example.com</td>
                                        <td class="py-4 px-6 text-gray-600">编辑员</td>
                                        <td class="py-4 px-6">
                                            <div class="badge badge-success badge-outline py-2 px-3 rounded-full">启用
                                            </div>
                                        </td>
                                        <td class="py-4 px-6 text-gray-500">2023-05-19 10:15</td>
                                        <td class="py-4 px-6 text-right">
                                            <div class="flex justify-end space-x-2">
                                                <button class="btn btn-sm btn-info rounded-lg">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button class="btn btn-sm btn-error rounded-lg">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                    <tr class="hover:bg-indigo-50 transition-colors">
                                        <td class="py-4 px-6 font-medium">viewer</td>
                                        <td class="py-4 px-6 text-gray-600">viewer@example.com</td>
                                        <td class="py-4 px-6 text-gray-600">查看员</td>
                                        <td class="py-4 px-6">
                                            <div class="badge badge-error badge-outline py-2 px-3 rounded-full">禁用</div>
                                        </td>
                                        <td class="py-4 px-6 text-gray-500">2023-05-18 09:45</td>
                                        <td class="py-4 px-6 text-right">
                                            <div class="flex justify-end space-x-2">
                                                <button class="btn btn-sm btn-info rounded-lg">
                                                    <i class="fas fa-edit"></i>
                                                </button>
                                                <button class="btn btn-sm btn-error rounded-lg">
                                                    <i class="fas fa-trash"></i>
                                                </button>
                                            </div>
                                        </td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>



<script>


    // 身份验证检查
    (function() {
        if (sessionStorage.getItem('authChecked')) {
            return;
        }

        const token = localStorage.getItem('token');
        if (!token) {
            window.location.href = '/login.html';
            return;
        }

        const xhr = $.ajax({
            url: CONFIG.API_BASE_URL + '/api/v1/auth/verify-token',
            method: 'POST',
            headers: {
                'Authorization': 'Bearer ' + token
            },
            timeout: 5000,
            success: function(response) {
                sessionStorage.setItem('authChecked', 'true');
                document.dispatchEvent(new Event('authVerified'));
            },
            error: function(xhr, status, error) {
                console.log('Token验证失败:', error);
                localStorage.removeItem('token');
                window.location.href = '/login.html';
            }
        });

        setTimeout(function() {
            if (xhr.readyState !== 4) {
                xhr.abort();
                localStorage.removeItem('token');
                window.location.href = '/login.html';
            }
        }, 5000);
    })();

    // 等待身份验证完成后再初始化页面
    document.addEventListener('authVerified', function() {
        initializePage();
    });

    // 如果已经验证过（刷新页面情况），直接初始化
    $(document).ready(function() {
        if (sessionStorage.getItem('authChecked')) {
            initializePage();
        }
    });

    // 页面初始化
    function initializePage() {
        // 动态加载模态框
        $.get('modals.html', function(data) {
            $('body').append(data);
        });

        // 初始化各个模块
        initializeModals();
        initializeKeywords();
        initializeUsers();
        initializeNavigation();
        initializeCharts();
    }

    // 模态框相关功能
    function initializeModals() {
        // 通用模态框配置
        window.showGenericModal = function(config) {
            const modal = document.getElementById('genericModal');
            
            // 设置模态框标题和描述
            $('.modal-title-text').text(config.title || '模态框标题');
            $('.modal-description').text(config.description || '模态框描述');
            $('.modal-icon').attr('class', `modal-icon mr-3 ${config.icon || 'fas fa-info-circle'}`);
            $('.modal-submit-text').text(config.submitText || '保存');
            $('.modal-submit-icon').attr('class', `modal-submit-icon mr-2 ${config.submitIcon || 'fas fa-save'}`);
            
            // 清空并生成表单内容
            const form = $('#genericModalForm');
            form.empty();
            
            // 生成表单字段
            if (config.fields && Array.isArray(config.fields)) {
                config.fields.forEach(field => {
                    const fieldElement = generateFieldElement(field);
                    form.append(fieldElement);
                });
            }
            
            // 设置提交事件
            $('#genericModalSubmit').off('click').on('click', function() {
                const formData = getFormData(config.fields);
                if (config.onSubmit) {
                    config.onSubmit(formData);
                }
            });
            
            // 显示模态框
            if (modal) {
                modal.showModal();
            }
        };
        
        // 生成字段元素
        window.generateFieldElement = function(field) {
            const fieldId = `field_${field.name}`;
            
            switch (field.type) {
                case 'text':
                case 'email':
                case 'password':
                    return `
                        <div class="form-control">
                            <label class="floating-label">
                                <span>${field.label}</span>
                                <input 
                                    type="${field.type}" 
                                    id="${fieldId}"
                                    placeholder="${field.placeholder || ''}" 
                                    class="input input-bordered w-full py-3 rounded-xl border-gray-300 focus:outline-none focus:ring-2 focus:ring-indigo-300"
                                    ${field.required ? 'required' : ''}
                                    ${field.value ? `value="${field.value}"` : ''}
                                />
                            </label>
                        </div>
                    `;
                case 'checkbox':
                    return `
                        <div class="form-control flex flex-row items-center py-2">
                            <label for="${fieldId}" class="cursor-pointer mr-5 text-base-content">
                                ${field.label}
                            </label>
                            <input type="checkbox" id="${fieldId}" class="toggle toggle-primary" ${field.value === 'enabled' ? 'checked' : ''} />
                        </div>
                    `;
                case 'textarea':
                    return `
                        <div class="form-control">
                            <label class="floating-label">
                                <span>${field.label}</span>
                                <textarea 
                                    id="${fieldId}"
                                    placeholder="${field.placeholder || ''}" 
                                    class="textarea textarea-bordered w-full py-3 rounded-xl h-32 border-gray-300 focus:outline-none focus:ring-2 focus:ring-indigo-300"
                                    ${field.required ? 'required' : ''}
                                >${field.value || ''}</textarea>
                            </label>
                        </div>
                    `;
                case 'select':
                    let options = '';
                    if (field.options && Array.isArray(field.options)) {
                        field.options.forEach(option => {
                            const selected = field.value === option.value ? 'selected' : '';
                            options += `<option value="${option.value}" ${selected}>${option.label}</option>`;
                        });
                    }
                    return `
                        <div class="form-control">
                            <label class="floating-label">
                                <span>${field.label}</span>
                                <select 
                                    id="${fieldId}"
                                    class="select select-bordered w-full py-3 rounded-xl border-gray-300 focus:outline-none focus:ring-2 focus:ring-indigo-300 appearance-none"
                                    ${field.required ? 'required' : ''}
                                >
                                    ${options}
                                </select>
                            </label>
                        </div>
                    `;
                default:
                    return '';
            }
        };
        
        // 获取表单数据
        window.getFormData = function(fields) {
            const data = {};
            fields.forEach(field => {
                const fieldId = `field_${field.name}`;
                const element = document.getElementById(fieldId);
                if (element) {
                    if (field.type === 'checkbox') {
                        data[field.name] = element.checked;
                    } else {
                        data[field.name] = element.value;
                    }
                }
            });
            return data;
        };
        
        // 关闭模态框
        window.closeGenericModal = function() {
            const modal = document.getElementById('genericModal');
            if (modal) {
                modal.close();
            }
        };
    }

    // 关键词管理功能
    function initializeKeywords() {
        // 获取所有关键词
        function getAllKeywords() {
            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = '/login.html';
                return;
            }

            $.ajax({
                url: CONFIG.API_BASE_URL + '/api/v1/keywords/?skip=0&limit=100',
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(response) {
                    renderKeywordsList(response);
                },
                error: function(xhr, status, error) {
                    console.log('获取关键词列表失败:', error);
                    if (xhr.status === 401) {
                        localStorage.removeItem('token');
                        window.location.href = '/login.html';
                    }
                }
            });
        }

        // 渲染关键词列表
        function renderKeywordsList(keywords) {
            const tbody = $('#keywords tbody');
            tbody.empty();

            if (!keywords || keywords.length === 0) {
                tbody.append(`
                    <tr>
                        <td colspan="6" class="py-8 px-6 text-center text-gray-500">
                            <div class="flex flex-col items-center justify-center">
                                <i class="fas fa-key text-3xl text-gray-300 mb-2"></i>
                                <span class="text-lg">暂无关键词数据</span>
                                <span class="text-sm text-gray-400 mt-1">点击"添加关键词"按钮创建新的关键词</span>
                            </div>
                        </td>
                    </tr>
                `);
                return;
            }

            keywords.forEach(keyword => {
                const statusBadge = keyword.is_active
                    ? '<span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-green-100 text-green-800"><i class="fas fa-check-circle mr-1"></i> 启用</span>'
                    : '<span class="inline-flex items-center px-3 py-1 rounded-full text-sm font-medium bg-red-100 text-red-800"><i class="fas fa-times-circle mr-1"></i> 禁用</span>';

                const createdAt = keyword.created_at
                    ? new Date(keyword.created_at).toLocaleDateString('zh-CN', {
                        year: 'numeric',
                        month: '2-digit',
                        day: '2-digit',
                        hour: '2-digit',
                        minute: '2-digit'
                    })
                    : '未知时间';

                const row = `
                    <tr class="hover:bg-indigo-50 transition-all duration-200 border-b border-gray-100 last:border-b-0">
                        <td class="py-4 px-6">
                            <div class="font-semibold text-gray-900">${keyword.keyword}</div>
                        </td>
                        <td class="py-4 px-6">
                            <div class="text-gray-600 max-w-xs truncate" title="${keyword.response}">${keyword.response}</div>
                        </td>
                        <td class="py-4 px-6">
                            <div class="flex items-center">
                                <span class="inline-flex items-center justify-center w-8 h-8 rounded-full bg-indigo-100 text-indigo-800 font-medium">${keyword.priority}</span>
                            </div>
                        </td>
                        <td class="py-4 px-6">
                            ${statusBadge}
                        </td>
                        <td class="py-4 px-6">
                            <div class="text-gray-500 text-sm">
                                <i class="far fa-calendar-alt mr-2"></i>${createdAt}
                            </div>
                        </td>
                        <td class="py-4 px-6 text-right">
                            <div class="flex justify-end space-x-2">
                                <button class="btn btn-sm btn-ghost btn-circle edit-keyword hover:bg-indigo-100 hover:text-indigo-600 transition-all" data-id="${keyword.id}" title="编辑">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn btn-sm btn-ghost btn-circle delete-keyword hover:bg-red-100 hover:text-red-600 transition-all" data-id="${keyword.id}" title="删除">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                        </td>
                    </tr>
                `;
                tbody.append(row);
            });
        }

        // 添加关键词按钮点击事件
        $(document).on('click', '#showAddKeywordModal', function() {
            showGenericModal({
                title: '添加关键词',
                description: '请输入关键词和对应的回复内容',
                icon: 'fas fa-key',
                submitText: '保存',
                submitIcon: 'fas fa-save',
                fields: [
                    {
                        name: 'keyword',
                        label: '关键词',
                        type: 'text',
                        placeholder: '请输入关键词',
                        icon: 'fas fa-font',
                        required: true
                    },
                    {
                        name: 'response',
                        label: '回复内容',
                        type: 'textarea',
                        placeholder: '请输入回复内容',
                        icon: 'fas fa-comment',
                        required: true
                    },
                    {
                        name: 'priority',
                        label: '优先级',
                        type: 'text',
                        placeholder: '请输入优先级',
                        icon: 'fas fa-sort-numeric-up',
                        required: true
                    },
                    {
                        name: 'is_active',
                        label: '状态',
                        type: 'checkbox',
                        icon: 'fas fa-toggle-on',
                        value: 'enabled'
                    }
                ],
                onSubmit: function(data) {
                    addKeyword(data);
                }
            });
        });

        // 添加关键词到服务器
        function addKeyword(keywordData) {
            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = '/login.html';
                return;
            }

            const requestData = {
                keyword: keywordData.keyword,
                response: keywordData.response,
                priority: parseInt(keywordData.priority) || 1,
                is_active: keywordData.is_active === true || keywordData.is_active === 'enabled'
            };

            $.ajax({
                url: CONFIG.API_BASE_URL + '/api/v1/keywords/',
                method: 'POST',
                headers: {
                    'Authorization': 'Bearer ' + token,
                    'Content-Type': 'application/json'
                },
                data: JSON.stringify(requestData),
                success: function(response) {
                    closeGenericModal();
                    showSuccessMessage('关键词添加成功');
                    getAllKeywords();
                },
                error: function(xhr, status, error) {
                    showErrorMessage('关键词添加失败: ' + (xhr.responseJSON?.detail || '未知错误'));
                    if (xhr.status === 401) {
                        localStorage.removeItem('token');
                        window.location.href = '/login.html';
                    }
                }
            });
        }

        // 编辑关键词按钮点击事件
        $(document).on('click', '.edit-keyword', function() {
            const keywordId = $(this).data('id');
            getKeywordDetail(keywordId);
        });

        // 获取关键词详细信息
        function getKeywordDetail(keywordId) {
            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = '/login.html';
                return;
            }

            $.ajax({
                url: CONFIG.API_BASE_URL + `/api/v1/keywords/${keywordId}`,
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(response) {
                    showEditKeywordModal(response);
                },
                error: function(xhr, status, error) {
                    showErrorMessage('获取关键词详情失败: ' + (xhr.responseJSON?.detail || '未知错误'));
                    if (xhr.status === 401) {
                        localStorage.removeItem('token');
                        window.location.href = '/login.html';
                    }
                }
            });
        }

        // 显示编辑关键词模态框
        function showEditKeywordModal(keywordData) {
            showGenericModal({
                title: '编辑关键词',
                description: '修改关键词和对应的回复内容',
                icon: 'fas fa-key',
                submitText: '更新',
                submitIcon: 'fas fa-save',
                fields: [
                    {
                        name: 'keyword',
                        label: '关键词',
                        type: 'text',
                        placeholder: '请输入关键词',
                        icon: 'fas fa-font',
                        required: true,
                        value: keywordData.keyword
                    },
                    {
                        name: 'response',
                        label: '回复内容',
                        type: 'textarea',
                        placeholder: '请输入回复内容',
                        icon: 'fas fa-comment',
                        required: true,
                        value: keywordData.response
                    },
                    {
                        name: 'priority',
                        label: '优先级',
                        type: 'text',
                        placeholder: '请输入优先级',
                        icon: 'fas fa-sort-numeric-up',
                        required: true,
                        value: keywordData.priority
                    },
                    {
                        name: 'is_active',
                        label: '状态',
                        type: 'checkbox',
                        icon: 'fas fa-toggle-on',
                        value: keywordData.is_active ? 'enabled' : ''
                    }
                ],
                onSubmit: function(data) {
                    updateKeyword(keywordData.id, data);
                }
            });
        }

        // 更新关键词到服务器
        function updateKeyword(keywordId, keywordData) {
            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = '/login.html';
                return;
            }

            const requestData = {
                keyword: keywordData.keyword,
                response: keywordData.response,
                priority: parseInt(keywordData.priority) || 1,
                is_active: keywordData.is_active === true || keywordData.is_active === 'enabled'
            };

            $.ajax({
                url: CONFIG.API_BASE_URL + `/api/v1/keywords/${keywordId}`,
                method: 'PUT',
                headers: {
                    'Authorization': 'Bearer ' + token,
                    'Content-Type': 'application/json'
                },
                data: JSON.stringify(requestData),
                success: function(response) {
                    closeGenericModal();
                    showSuccessMessage('关键词更新成功');
                    getAllKeywords();
                },
                error: function(xhr, status, error) {
                    showErrorMessage('关键词更新失败: ' + (xhr.responseJSON?.detail || '未知错误'));
                    if (xhr.status === 401) {
                        localStorage.removeItem('token');
                        window.location.href = '/login.html';
                    }
                }
            });
        }

        // 删除关键词按钮点击事件
        $(document).on('click', '.delete-keyword', function() {
            const keywordId = $(this).data('id');
            const keywordName = $(this).closest('tr').find('td:first').text();
            showDeleteConfirmation(keywordId, keywordName);
        });

        // 显示删除确认对话框
        function showDeleteConfirmation(keywordId, keywordName) {
            const confirmHtml = `
                <div id="deleteConfirmModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
                    <div class="bg-white rounded-2xl shadow-2xl p-6 w-full max-w-md">
                        <div class="flex items-center justify-between mb-4">
                            <h3 class="text-xl font-bold text-gray-800">确认删除</h3>
                            <button id="closeDeleteModal" class="btn btn-sm btn-circle btn-ghost">
                                <i class="fas fa-times"></i>
                            </button>
                        </div>
                        <div class="mb-6">
                            <p class="text-gray-600">您确定要删除关键词 "<strong>${keywordName}</strong>" 吗？此操作不可撤销。</p>
                        </div>
                        <div class="flex justify-end space-x-3">
                            <button id="cancelDelete" class="btn btn-outline rounded-lg">取消</button>
                            <button id="confirmDelete" class="btn btn-error rounded-lg" data-id="${keywordId}">
                                <i class="fas fa-trash mr-2"></i>确认删除
                            </button>
                        </div>
                    </div>
                </div>
            `;
            $('body').append(confirmHtml);
        }

        // 关闭删除确认对话框
        $(document).on('click', '#closeDeleteModal, #cancelDelete', function() {
            $('#deleteConfirmModal').remove();
        });

        // 确认删除按钮点击事件
        $(document).on('click', '#confirmDelete', function() {
            const keywordId = $(this).data('id');
            deleteKeyword(keywordId);
        });

        // 删除关键词
        function deleteKeyword(keywordId) {
            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = '/login.html';
                return;
            }

            $.ajax({
                url: CONFIG.API_BASE_URL + `/api/v1/keywords/${keywordId}`,
                method: 'DELETE',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(response) {
                    $('#deleteConfirmModal').remove();
                    showSuccessMessage('关键词删除成功');
                    getAllKeywords();
                },
                error: function(xhr, status, error) {
                    $('#deleteConfirmModal').remove();
                    showErrorMessage('关键词删除失败: ' + (xhr.responseJSON?.detail || '未知错误'));
                    if (xhr.status === 401) {
                        localStorage.removeItem('token');
                        window.location.href = '/login.html';
                    }
                }
            });
        }

        // 显示成功消息
        function showSuccessMessage(message) {
            const alertHtml = `
                <div id="successAlert" class="alert alert-success mb-6">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 shrink-0 stroke-current" fill="none" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    <span>${message}</span>
                </div>
            `;
            $('#keywords .flex.flex-col.sm\\:flex-row').after(alertHtml);
            
            setTimeout(function() {
                $('#successAlert').fadeOut(500, function() {
                    $(this).remove();
                });
            }, 3000);
        }

        // 显示错误消息
        function showErrorMessage(message) {
            const alertHtml = `
                <div id="errorAlert" class="alert alert-error mb-6">
                    <svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 shrink-0 stroke-current" fill="none" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    <span>${message}</span>
                </div>
            `;
            $('#keywords .flex.flex-col.sm\\:flex-row').after(alertHtml);
            
            setTimeout(function() {
                $('#errorAlert').fadeOut(500, function() {
                    $(this).remove();
                });
            }, 3000);
        }

        // 初始化关键词列表
        getAllKeywords();
    }

    // 用户管理功能
    function initializeUsers() {
        // 获取当前用户详细信息
        function getCurrentUser() {
            const token = localStorage.getItem('token');
            if (!token) {
                window.location.href = '/login.html';
                return;
            }

            $.ajax({
                url: CONFIG.API_BASE_URL + '/api/v1/users/me',
                method: 'GET',
                headers: {
                    'Authorization': 'Bearer ' + token
                },
                success: function(response) {
                    localStorage.setItem('currentUser', JSON.stringify(response));
                    renderUserInfo(response);
                },
                error: function(xhr, status, error) {
                    console.log('获取用户信息失败:', error);
                    if (xhr.status === 401) {
                        localStorage.removeItem('token');
                        window.location.href = '/login.html';
                    }
                }
            });
        }

        // 渲染用户信息
        function renderUserInfo(user) {
            $('#username').text(user.username || user.name || '管理员');
            $('#email').text(user.email || 'admin@example.com');
        }

        // 初始化用户信息
        getCurrentUser();
    }

    // 导航功能
    function initializeNavigation() {
        // 菜单切换
        $('.menu-item').on('click', function(e) {
            e.preventDefault();
            
            $('.menu-item').removeClass('active');
            $(this).addClass('active');
            
            const target = $(this).data('target');
            $('.content-section').removeClass('active');
            $('#' + target).addClass('active');
            
            const title = $(this).find('span').text();
            $('#pageTitle').text(title);
        });

        // 登出按钮
        $('#logoutBtn').on('click', function() {
            localStorage.removeItem('token');
            localStorage.removeItem('currentUser');
            sessionStorage.removeItem('authChecked');
            window.location.href = '/login.html';
        });
    }

    // 图表功能
    function initializeCharts() {
        const ctx = document.getElementById('messageChart').getContext('2d');
        const messageChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                datasets: [{
                    label: '消息数量',
                    data: [120, 150, 180, 220, 190, 250, 326],
                    borderColor: '#818cf8',
                    backgroundColor: 'rgba(129, 140, 248, 0.1)',
                    borderWidth: 3,
                    pointBackgroundColor: '#818cf8',
                    pointRadius: 5,
                    pointHoverRadius: 7,
                    fill: true,
                    tension: 0.4
                }]
            },
            options: {
                responsive: true,
                maintainAspectRatio: false,
                plugins: {
                    legend: {
                        display: false
                    }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)'
                        }
                    },
                    x: {
                        grid: {
                            color: 'rgba(0, 0, 0, 0.05)'
                        }
                    }
                }
            }
        });
    }
</script>
</body>

</html>